import {
  MaterialApi,
  modifyMaterialAtlas,
} from '@/api/premium/content/material'
import { ModifyMaterialAtlasRequest } from '@/api/premium/content/model/materialModel'
import { MaterialItem } from '@/components/ItemList/MaterialList/types'
import { useStore } from '@/store'
import { message } from 'ant-design-vue'
import { cloneDeep, isEqual } from 'lodash-es'
import { computed, ref } from 'vue'
import { ListMaterialItem } from '../types'

/**
 * 处理编辑当前素材的图集相关
 *
 * @param searchApi 刷新素材列表函数
 */
const useEditAtlas = (searchApi: () => Promise<void>) => {
  const store = useStore()
  /** 当前选中的图集 */
  const selectedAtlas = ref<string[]>([])
  /** 缓存当前素材已有图集, 用于计算增量修改，监看当前选择的项目是否变化等等 */
  const tempSelectedAtlas = ref<string[]>([])
  /**
   * 打开编辑图集的pop弹框
   *
   * @param item 当前素材项
   */
  const openEditAtlas = async (item: ListMaterialItem) => {
    // 先清空之前的已选图集和图集缓存
    selectedAtlas.value = []
    tempSelectedAtlas.value = []
    if (item.atlas) {
      tempSelectedAtlas.value = item.atlas.map((atlas) => atlas.id)
      selectedAtlas.value = cloneDeep(tempSelectedAtlas.value)
    }
  }

  /**
   * 确认修改当前素材项的图集列表[传全量图集列表数据]
   * 如果又要改成增量数据
   * selectedAtlas.value 要变为 selectedAtlas.value.filter(atlasId => !tempSelectedAtlas.value.includes(atlasId))
   */
  const confirmAddAtlas = async (materialItem: MaterialItem) => {
    if (isEqual(selectedAtlas.value, tempSelectedAtlas.value)) {
      // 没有修改啥都不做
    } else if (selectedAtlas.value.length <= 0) {
      message.error(
        '添加失败，没有与当前素材相匹配的图集，请先添加当前类型的图集！'
      )
    } else {
      const reqData: ModifyMaterialAtlasRequest = {
        materialId: materialItem.id || '',
        data: selectedAtlas.value,
      }
      await modifyMaterialAtlas(reqData)
      message.success('修改成功')
      await searchApi()
    }
    selectedAtlas.value = []
  }
  const modifyMaterialAtlasLoading = computed(() =>
    store.getters['global/isOpLoading'](MaterialApi.MODIFY_MATERIAL_ATLAS)
  )

  const removeMaterialAtlasLoading = computed(() =>
    store.getters['global/isOpLoading'](MaterialApi.REMOVE_MATERIAL_ATLAS)
  )

  /**
   * 退出添加图集pop弹框的回调
   */
  const cancelAddAtlas = () => {
    selectedAtlas.value = []
  }

  return {
    selectedAtlas,
    confirmAddAtlas,
    cancelAddAtlas,
    tempSelectedAtlas,
    openEditAtlas,
    modifyMaterialAtlasLoading,
    removeMaterialAtlasLoading,
  }
}

export default useEditAtlas
